package com.chookss.home.logContacts;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.LogEntity;
import com.chookss.home.entity.LogFilesEntity;
import com.chookss.home.knowledge.adaper.LogDocunmentAdapter;
import com.chookss.home.publish.UploadLogService;
import com.chookss.home.publish.adapter.MyImagsAdapter;
import com.chookss.mine.personal.MyLogActivity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.DrawableTextView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LogDetailActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView tvLogsTitle;
    @BindView(R.id.tvTitle1)
    TextView tvTitle1;
    @BindView(R.id.tvConent1)
    TextView tvConent1;
    @BindView(R.id.tvTitle2)
    TextView tvTitle2;
    @BindView(R.id.tvConent2)
    TextView tvConent2;
    @BindView(R.id.tvTitle3)
    TextView tvTitle3;
    @BindView(R.id.tvConent3)
    TextView tvConent3;
    @BindView(R.id.tvTitle4)
    TextView tvTitle4;
    @BindView(R.id.tvConent4)
    TextView tvConent4;
    @BindView(R.id.tvTitle5)
    TextView tvTitle5;
    @BindView(R.id.tvConent5)
    TextView tvConent5;
    @BindView(R.id.tvFailure)
    TextView tvFailure;
    @BindView(R.id.tvGroup)
    TextView tvGroup;
    @BindView(R.id.llMiddle)
    LinearLayout llMiddle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rlGroup)
    RelativeLayout rlGroup;
    @BindView(R.id.documentRecyclerView)
    RecyclerView documentRecyclerView;
    @BindView(R.id.llDocument)
    LinearLayout llDocument;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.spaceView)
    View spaceView;
    @BindView(R.id.tvReadMore)
    DrawableTextView tvReadMore;
    @BindView(R.id.ivHead1)
    CircleImageView ivHead1;
    @BindView(R.id.ivHead2)
    CircleImageView ivHead2;
    @BindView(R.id.ivHead3)
    CircleImageView ivHead3;
    @BindView(R.id.tvRead)
    TextView tvRead;
    @BindView(R.id.llRead)
    LinearLayout llRead;
    private LogEntity logEntity;
    private List<LogEntity.VideoBean> picVideoList = new ArrayList<>();
    private List<LogEntity.DocunmentBean> docunmentBeanList = new ArrayList<>();
    private LogDocunmentAdapter docunmentListAdapter;
    private MyImagsAdapter myImagsAdapter;
    private int status = 1;//1正常 0上传中 2失败
    private String TAG = "LogDetailActivity_DownloadFile";
    private int position=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logs_detail);
        ButterKnife.bind(this);
        initState();

    }

    @Override
    public void initData() {
        logEntity = (LogEntity) getIntent().getSerializableExtra("data");
        position=getIntent().getIntExtra("position",0);
        KLog.i(status + "------");
        if (Utils.isNull(logEntity.getCache())) {
            status = 1;
        } else {
            if (0 == logEntity.getCacheStatus()) {
                status = 0;
            } else if (2 == logEntity.getCacheStatus()) {
                status = 2;
            }
        }

        registerBoradcastReceiver();
        if (!Utils.isNull(logEntity.getTeamCode())) {
            rlGroup.setVisibility(View.VISIBLE);
            String code = logEntity.getTeamCode();
            tvGroup.setText(logEntity.getTeamName() + "(" + code.substring(code.length() - 10, code.length()) + ")");
        }
//        日志类型 0 日报 1 周报 2 月报 3 日志
//        String remark=logEntity.getRemark();
        if ("3".equals(logEntity.getReportType())) {
            tvTitle1.setText("标题");
            tvConent1.setText(logEntity.getTitle());
            tvTitle2.setText("内容");
            tvConent2.setText(logEntity.getContent());
            tvLogsTitle.setText(logEntity.getEmployeeName() + "的日志");
        } else if ("0".equals(logEntity.getReportType())) {
            tvTitle1.setText("今日完成工作");
            tvConent1.setText(logEntity.getFinishWork());
            tvTitle2.setText("未完成工作");
            tvConent2.setText(logEntity.getUnFinishWork());
            tvTitle3.setText("需协调工作");
            tvConent3.setText(logEntity.getNeedHelpWork());
            tvTitle4.setText("明日工作计划");
            tvConent4.setText(logEntity.getNextWorkPlan());
            tvTitle5.setText("备注");
            tvConent5.setText(logEntity.getRemark());
            tvLogsTitle.setText(logEntity.getEmployeeName() + "的日报");
        } else if ("1".equals(logEntity.getReportType())) {
            tvTitle1.setText("本周完成工作");
            tvConent1.setText(logEntity.getFinishWork());
            tvTitle2.setText("本周工作总结");
            tvConent2.setText(logEntity.getUnFinishWork());
            tvTitle3.setText("下周工作计划");
            tvConent3.setText(logEntity.getNextWorkPlan());
            tvTitle4.setText("需协调与帮助");
            tvConent4.setText(logEntity.getNeedHelpWork());
            tvTitle5.setText("备注");
            tvConent5.setText(logEntity.getRemark());
            tvLogsTitle.setText(logEntity.getEmployeeName() + "的周报");
        } else if ("2".equals(logEntity.getReportType())) {
            tvTitle1.setText("本月工作内容");
            tvConent1.setText(logEntity.getFinishWork());
            tvTitle2.setText("本月工作总结");
            tvConent2.setText(logEntity.getUnFinishWork());
            tvTitle3.setText("下月工作计划");
            tvConent3.setText(logEntity.getNextWorkPlan());
            tvTitle4.setText("需帮助与支持");
            tvConent4.setText(logEntity.getNeedHelpWork());
            tvTitle5.setText("备注");
            tvConent5.setText(logEntity.getRemark());
            tvLogsTitle.setText(logEntity.getEmployeeName() + "的月报");
        }
        if ("3".equals(logEntity.getReportType())) {
            llMiddle.setVisibility(View.GONE);
        } else {
            llMiddle.setVisibility(View.VISIBLE);
            if (Utils.isNull(logEntity.getRemark())) {
                tvConent5.setText("无");
            }
        }
        String title = getIntent().getStringExtra("title");
        if (!Utils.isNull(title)) {
            tvLogsTitle.setText(title);
            tvLogsTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        }
        documentRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        docunmentListAdapter = new LogDocunmentAdapter(R.layout.item_knowledge_look, this, docunmentBeanList, status, TAG);
        documentRecyclerView.setAdapter(docunmentListAdapter);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        myImagsAdapter = new MyImagsAdapter(R.layout.item_publish_log, this, picVideoList, status);
        recyclerView.setAdapter(myImagsAdapter);
        NavigationTools.setWaterMark(this, "14");
        if (status == 1) {
            getData();
            NavigationTools.saveUseRecord(this, "1", "02");
        } else {
            if (status == 2) {
                //上传失败
                tvFailure.setVisibility(View.VISIBLE);
                llBottom.setVisibility(View.VISIBLE);
                llDocument.setVisibility(View.VISIBLE);
            } else {
                //上传中
                tvFailure.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                picVideoList.addAll(logEntity.getVideoBeanlist());
                docunmentBeanList.addAll(logEntity.getDocunmentBeanlist());
                myImagsAdapter.notifyDataSetChanged();
                docunmentListAdapter.notifyDataSetChanged();
                setPicUrlList();
                if ((logEntity.getVideoBeanlist().size() + logEntity.getDocunmentBeanlist().size()) > 0) {
                    llDocument.setVisibility(View.VISIBLE);
                } else {
                    llDocument.setVisibility(View.GONE);
                }
            }
        }
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("reportCode", logEntity.getReportCode());
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<LogFilesEntity>>() {
        }.getType(), null, Urls.getReportFile, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<LogFilesEntity>() {
            @Override
            public void onSuccess(LogFilesEntity data) {
                if (data != null) {
                    if (data.getPlayPage().getList().size() > 0 && status == 1) {
                        spaceView.setVisibility(View.VISIBLE);
                        llRead.setVisibility(View.VISIBLE);
                        String names = "";
                        for (int i = 0; i < data.getPlayPage().getList().size(); i++) {
                            if (Utils.isNull(names)) {
                                names = names + "" + data.getPlayPage().getList().get(i).getPlayEmployeeName();
                            } else {
                                names = names + "、" + data.getPlayPage().getList().get(i).getPlayEmployeeName();
                            }
                            if (i == 0) {
                                ivHead1.setVisibility(View.VISIBLE);
                                GlideUtils.loadAvatar(LogDetailActivity.this, data.getPlayPage().getList().get(0).getHeadPhotoUrl(), ivHead1);
                            } else if (i == 1) {
                                ivHead2.setVisibility(View.VISIBLE);
                                GlideUtils.loadAvatar(LogDetailActivity.this, data.getPlayPage().getList().get(1).getHeadPhotoUrl(), ivHead2);
                            } else if (i == 2) {
                                ivHead3.setVisibility(View.VISIBLE);
                                GlideUtils.loadAvatar(LogDetailActivity.this, data.getPlayPage().getList().get(2).getHeadPhotoUrl(), ivHead3);
                            }
                        }
                        if (Utils.changeNumber(data.getPlayPage().getTotal()) > 3) {
                            tvRead.setText(names + "等" + data.getPlayPage().getTotal() + "人浏览过");
                        } else {
                            tvRead.setText(names + data.getPlayPage().getTotal() + "人浏览过");
                        }
                    }
                    List<LogFilesEntity.DatabaseBean> databaseBeanList = data.getDatabase();
                    List<String> pictureInfoList = data.getPictureList();
                    List<LogFilesEntity.VideoBean> videoList = data.getVideo();
                    for (int i = 0; i < pictureInfoList.size(); i++) {
                        LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                        videoBean.setType("0");
                        if (pictureInfoList.get(i).contains("x-oss-process")) {
                            videoBean.setUrl(pictureInfoList.get(i));
                        } else {
                            videoBean.setUrl(pictureInfoList.get(i) + "?x-oss-process=image/resize,m_lfit,h_400,w_400");// 缩略图url
                        }
                        picVideoList.add(videoBean);
                    }
                    for (int i = 0; i < videoList.size(); i++) {
                        LogEntity.VideoBean videoBean = new LogEntity.VideoBean();
                        videoBean.setType("1");
                        videoBean.setVideoId(videoList.get(i).getVideoId());
                        videoBean.setVideoCoverPath(videoList.get(i).getVideoCoverPath());
                        videoBean.setVideoTitle(videoList.get(i).getVideoTitle());
                        videoBean.setVideoSize(videoList.get(i).getVideoSize());
                        picVideoList.add(videoBean);
                    }
                    for (int i = 0; i < databaseBeanList.size(); i++) {
                        LogEntity.DocunmentBean docunmentBean = new LogEntity.DocunmentBean();
                        docunmentBean.setDataCode(databaseBeanList.get(i).getDataCode());
                        docunmentBean.setDataTime(databaseBeanList.get(i).getUploadTime());
                        docunmentBean.setDataPath(databaseBeanList.get(i).getDataPath());
                        docunmentBean.setDataSize(databaseBeanList.get(i).getDataSize());
                        docunmentBean.setDataTitle(databaseBeanList.get(i).getDataTitle());
                        docunmentBean.setDataType(databaseBeanList.get(i).getFileType());
                        docunmentBeanList.add(docunmentBean);
                    }
                    myImagsAdapter.notifyDataSetChanged();
                    docunmentListAdapter.notifyDataSetChanged();
                    setPicUrlList();
                }
                if ((picVideoList.size() + docunmentBeanList.size()) > 0) {
                    llDocument.setVisibility(View.VISIBLE);
                } else {
                    llDocument.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void setPicUrlList() {
        List<ImageInfo> imageInfoList = new ArrayList<>();
        for (int i = 0; i < picVideoList.size(); i++) {
            if (picVideoList.get(i).getType().equals("0")) {
                ImageInfo imageInfo = new ImageInfo();
                if (picVideoList.get(i).getUrl().contains("x-oss-process")) {
                    imageInfo.setThumbnailUrl(picVideoList.get(i).getUrl().split("\\?")[0]);// 缩略图url
                    imageInfo.setOriginUrl(picVideoList.get(i).getUrl().split("\\?")[0]);// 缩略图url
                } else {
                    imageInfo.setThumbnailUrl(picVideoList.get(i).getUrl());// 缩略图url
                    imageInfo.setOriginUrl(picVideoList.get(i).getUrl());// 缩略图url
                }

                imageInfoList.add(imageInfo);
            }
        }
        myImagsAdapter.setUrlList(imageInfoList);
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < docunmentBeanList.size(); i++) {
                    if (docunmentBeanList.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!docunmentBeanList.get(i).isOpen()) {
                            if (encryptStatus) {
                                docunmentBeanList.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }
                    }
                }

            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);
            }
        } else {
            if (position < 0) {
                return;
            }
            if (percent > 0 && percent < 100) {
                if (docunmentListAdapter != null) {
                    docunmentBeanList.get(position).setProgress(percent);
                    docunmentListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (docunmentListAdapter != null) {
                    docunmentBeanList.get(position).setProgress(100);
                    docunmentListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(LogDetailActivity.this, fileUrl, fileName, recevierDataCode, TAG);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(TAG);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @OnClick({R.id.common_title_back, R.id.tvReadMore, R.id.tv_publish})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvReadMore:
                intent = new Intent(this, LogReadsActivity.class);
                intent.putExtra("reportCode", logEntity.getReportCode());
                startActivity(intent);
                break;
            case R.id.tv_publish:
                HashMap<String, String> map = new HashMap<>();
                map.put("Log_Cache_Error_Position", position+"");
                EventBus.getDefault().post(new MyEvent(map));
                intent = new Intent(this, UploadLogService.class);
                intent.putExtra("logEntity", logEntity);
                intent.putExtra("cacheStatus", 3);
                startService(intent);
                finish();
                break;
        }
    }
}
